import { Server } from "http";
import { WebSocketServer, WebSocket } from "ws";
import { logger } from "../log";
import { genId } from "../utils/genId";
import { wsStore } from "./store";
import { handlerWsMsg } from "./msghandler";

export function initWebSocket(server: Server) {
  const wss = new WebSocketServer({ server });
  wss.on("connection", (ws) => {
    // 存储当前连接
    const id = genId();
    wsStore.add(id, ws);
    logger.info(`ws connected, id: ${id}, total: ${wsStore.size()}`);
    // 回调
    ws.send(JSON.stringify({ id }));

    ws.on("message", (data) => {
      handlerWsMsg({ id, msg: data.toString() });
    });
    ws.on("close", () => {
      wsStore.remove(id);
      logger.info(`ws disconnected, id: ${id}, total: ${wsStore.size()}`);
    });
  });

  wss.on("listening", () => {
    logger.info("--- WS server listening at 9527 ---");
  });
}
